//
//  PersonViewController.m
//  MidProject
//
//  Created by itlab on 2020/11/15.
//  Copyright © 2020 itlab. All rights reserved.
//

#import "PersonViewController.h"
#import "../Layout/TableListController.h"
#import "Masonry.h"
#import "AddinfViewController.h"
//#import "../Layout/LoadingTableViewCell.h"

@interface PersonViewController()

//@property LoadingStatus status;
@property(nonatomic, strong) NSDictionary *GetItem;

@property TableListController * Movie;
@property TableListController * App;
@property TableListController * Ablum;
@property UILabel * name;
@property UILabel * email;

@end

@implementation PersonViewController

-(void)viewDidLoad{
    [super viewDidLoad];
    
    NSLog(@"viewdidload!!!!+==");
    self.title = @"个人主页";
    
    // 三个列表；
    self.Movie = [TableListController new];
    self.Movie.table_name = @"Movie";
    self.App = [TableListController new];
    self.App.table_name = @"texts";
    self.Ablum = [TableListController new];
    self.Ablum.table_name = @"album";
    
    WMZPageParam *param = PageParam();
    param.wTitleArrSet(@[
                         @{
                             @"name":@"Text",
                             @"backgroundColor":@[PageColor(0x15314b),PageColor(0x009a93)]},
                         @{
                             @"name":@"Movie",
                             @"backgroundColor":@[PageColor(0xFFFEF7),PageColor(0xFFA500),],
                             @"indicatorColor":PageColor(0x9b4f2d),
                             @"titleSelectColor":PageColor(0x9b4f2d),
                             @"titleColor":PageColor(0xd79869)
                             },
                         @{
                             @"name":@"Ablum",
                             @"titleColor":PageColor(0xffaa68),
                             @"backgroundColor":@[PageColor(0xFFECEA),PageColor(0xd70022)],
                             @"indicatorColor":PageColor(0xfffcc6),
                             @"titleSelectColor":PageColor(0xfffcc6)
                             }
                         ])
    .wControllersSet(@[ self.App, self.Movie, self.Ablum])
    .wMenuTitleFontSet(17)
    .wScrollCanTransferSet(NO)
    .wMenuTitleWeightSet(120)
    .wMenuTitleColorSet(PageColor(0xeeeeee))
    .wMenuTitleSelectColorSet(PageColor(0xffffff))
    .wMenuIndicatorColorSet(PageColor(0x00dea3))
    .wMenuIndicatorWidthSet(40)
    .wMenuCellMarginSet(82)
    .wMenuAnimalTitleGradientSet(NO)
    .wTopSuspensionSet(YES)
    .wMenuAnimalSet(PageTitleMenuAiQY)
    .wTopSuspensionSet(YES)
    .wFromNaviSet(NO)
    .wMenuHeadViewSet(^UIView *{
        UIView *back = [UIView new];
        back.backgroundColor = [UIColor whiteColor];
        back.frame = CGRectMake(0, 0, PageVCWidth, 240+PageVCStatusBarHeight);
        UIImage * image = [UIImage imageNamed:@"backimage.jpg"];
        UIImageView * imgview = [[UIImageView alloc] initWithImage:image];
        [back addSubview:imgview];
        [imgview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(back.frame.size.width);
            make.height.mas_equalTo(back.frame.size.height);
            make.top.equalTo(back).offset(0);
            make.centerX.equalTo(back);
        }];
        
        //为图片透明度设置渐变效果
        
        UIColor *colorOne = [UIColor colorWithRed:(255/255.0)  green:(255/255.0)  blue:(255/255.0)  alpha:1.0];
        
        UIColor *colorTwo = [UIColor colorWithRed:(255/255.0)  green:(255/255.0)  blue:(255/255.0)  alpha:0.0];
        
        NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];
        
        CAGradientLayer *gradient = [CAGradientLayer layer];
        
        //设置开始和结束位置(设置渐变的方向)
        
        gradient.startPoint = CGPointMake(0, 1);
        
        gradient.endPoint = CGPointMake(0, 0);
        
        gradient.colors = colors;
        
        gradient.frame = CGRectMake(0, 0, PageVCWidth, 240+PageVCStatusBarHeight);
        
        [imgview.layer insertSublayer:gradient atIndex:0];
        
        // 添加用户头像
        UIImage * userimage = [UIImage imageNamed:@"login.png"];
        UIImageView * userimgview = [[UIImageView alloc] initWithImage:userimage];
        // 设置边框颜色为灰色；
        CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
        CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0.1,0,0,0.1});
        
        // 设置图片的边框的宽度，颜色和形状；
        [userimgview.layer setBorderWidth:2];
        [userimgview.layer setBorderColor:color];
        [userimgview.layer setCornerRadius:40];
        [userimgview.layer setMasksToBounds:YES];
        [userimgview setBackgroundColor:[UIColor clearColor]];
        [back addSubview:userimgview];
        
        // 约束条件设置；
        [userimgview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(80);
            make.height.mas_equalTo(80);
            make.top.equalTo(back).offset(80);
            make.left.equalTo(back).offset((back.frame.size.width-80)/2);
        }];
        
        
        // 添加用户信息
        self.name = [[UILabel alloc] init];
        self.email = [[UILabel alloc] init];
        [self GetSelf:@"http://172.18.178.56/api/user/info/self"];
        
        if ([[self.GetItem valueForKey:@"State"] isEqualToString:@"not_login"]){
            self.name.text = @"未登录";
            self.email.text = @"";
        }
        else{
            self.name.text = self->_GetItem[@"Name"];
            self.email.text = self->_GetItem[@"Email"];
        }
        [back addSubview:self.name];
        [back addSubview:self.email];
        // 约束条件设置；
        [self.name mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(userimgview.mas_bottom).offset(20);
            make.centerX.equalTo(userimgview.mas_centerX);
        }];
        [self.email mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(userimgview.mas_bottom).offset(40);
            make.centerX.equalTo(userimgview.mas_centerX);
        }];
        
        
        // 添加动态按钮
        UIButton * add = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [add setTitle:@"添加动态" forState:UIControlStateNormal];
        [add.layer setBorderWidth:2];
        [add.layer setBorderColor:color];
        [add setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [add setBackgroundColor:[UIColor whiteColor]];
        add.titleLabel.font = [UIFont systemFontOfSize: 12.0];
        add.layer.cornerRadius = 10;
        [add addTarget:self action:@selector(fabu_on_click:) forControlEvents:UIControlEventTouchDown];
        [add addTarget:self action:@selector(fabu_click_end:) forControlEvents:UIControlEventTouchUpInside];
        [back addSubview:add];
        [add mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(80);
            make.right.equalTo(back).offset(-20);
            make.bottom.equalTo(back).offset(-20);
            make.height.mas_equalTo(40);
        }];
        
        return back;
    });
    self.param = param;
}

- (void)fabu_on_click: (UIButton *)sender{
    //[sender setBackgroundColor:[UIColor blueColor]];
    AddinfViewController * add = [[AddinfViewController alloc] init];
    [add setPersonViewController:self];
    [self.navigationController pushViewController:add animated:YES];
    NSLog(@"打卡界面还在制作");
}

- (void)fabu_click_end:(UIButton *) sender{
    //[sender setBackgroundColor:[UIColor whiteColor]];
    NSLog(@"click end");
}

// GET 获取个人文本、相册的API（Movie没有相关的接口）
//当前页面添加

// NSString *urlString = @"http://172.18.178.56/api/content/texts/self"; 获取个人
// NSString *urlString  =@"http://172.18.178.56/api/content/album/self"     获取相册
-(void) GetSelf:(NSString*) urlString{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    request.timeoutInterval = 60;
    NSURLSession *session = [NSURLSession sharedSession];
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    NSError *jsonError;
                                                    self->_GetItem = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
                                                    if(jsonError) {
                                                        // check the error description
                                                        NSLog(@"json error : %@", [jsonError localizedDescription]);
                                                    } else {
                                                        // use the jsonDictionaryOrArray
                                                        NSLog(@"json : %@",self->_GetItem);
                                                    }
                                                    dispatch_semaphore_signal(semaphore);
                                                }];
    [dataTask resume];
    dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
}

- (void)reloadData{
    NSLog(@"reload");
    [self GetSelf:@"http://172.18.178.56/api/user/info/self"];
    
    if ([[self.GetItem valueForKey:@"State"] isEqualToString:@"not_login"]){
        self.name.text = @"未登录";
        self.email.text = @"";
    }
    else{
        self.name.text = self->_GetItem[@"Name"];
        self.email.text = self->_GetItem[@"Email"];
    }
    [self.Ablum reloadData];
    [self.App reloadData];
    [self.Movie reloadData];
//    [self viewDidLoad];
}

-(void)viewWillAppear:(BOOL)animated{
    dispatch_async(dispatch_get_main_queue(), ^{
//        [self viewDidLoad];
        [self reloadData];
    });
}

@end